package lovemusic.lanou.com.newsmusic.service;

import android.app.Service;
import android.content.Intent;
import android.graphics.LinearGradient;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.format.DateUtils;
import android.util.Log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import lovemusic.lanou.com.newsmusic.models.MusicInfo;
import lovemusic.lanou.com.newsmusic.ui.activity.BaseActivity;
import lovemusic.lanou.com.newsmusic.utils.MusicUtils;
import lovemusic.lanou.com.newsmusic.utils.Preferences;
import lovemusic.lanou.com.newsmusic.utils.SystemUtils;
import lovemusic.lanou.com.newsmusic.utils.UIUtils;

/**
 * 音乐播放的服务
 * Created by lanouhn on 2016/9/29.
 */
public class PlayMusicService extends Service implements MediaPlayer.OnCompletionListener{

    // 定义一个更新进度条的时间常量
    private static final long TIME_UPDATE = 100L;
    // 本地歌曲列表
    public List<MusicInfo> sMusicList = new ArrayList<>();
    // 正在播放的歌曲[本地|网络]
    private MusicInfo mPlayingMusic;
    // 正在播放的本地歌曲的序号
    public int mPlayingPosition=0;
    // 播放音乐进度的接口
    public OnPlayerEventListener mListener;
    // 定义一个布尔类型判断音乐是否正在播放
    private boolean isPause = false;
    //定义定时播放的一个剩余时间单位
    private long quitTimerRemain;
    //定义一个用来装启动Activity的集合
    private static final List<BaseActivity> sActivityStack = new ArrayList<>();
//    定义一个播放
    private MediaPlayer mediaPlayer = new MediaPlayer();


    @Override
    public void onCreate() {
        super.onCreate();
        sMusicList=MusicUtils.getMusicDate();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new PlayBinder();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    public  List<MusicInfo> getMusicList() {
//        sMusicList=MusicUtils.getMusicDate();
        return sMusicList;
    }

    public void setOnPlayEventListener(OnPlayerEventListener listener) {
        mListener = listener;
    }

    /**
     * 更新音乐列表
     */
    public void updateMusicList() {
        if (MusicUtils.getMusicDate().size() > 0) {
            sMusicList.clear();
            getMusicList().addAll(MusicUtils.getMusicDate());
        }
        mPlayingMusic = mPlayingMusic == null ? sMusicList.get(mPlayingPosition) : mPlayingMusic;
    }


    public int play(int position) {
        if (getMusicList().isEmpty()) {
            return -1;
        }
        if (position < 0) {
            position = getMusicList().size() - 1;
        } else if (position >= getMusicList().size()) {
            position = 0;
        }
        mPlayingPosition = position;
        mPlayingMusic = getMusicList().get(position);

        try {
//          重置MediaPlayer的初始化状态。在调用此方法，您将必须通过设置
//          数据源和调用prepare()
            mediaPlayer.reset();
            mediaPlayer.setDataSource(mPlayingMusic.getUri());
            mediaPlayer.prepare();
//          开始或者恢复播放音乐
            mediaPlayer.start();
            isPause = false;
            UIUtils.getHandle().post(mBackgroudRunable);
            if (mListener != null) {
                mListener.onChange(mPlayingMusic);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Preferences.saveCurrentSongId(mPlayingMusic.getId());
        return mPlayingPosition;

    }

    ;


    public void play(MusicInfo musicInfo) {
        mPlayingMusic = musicInfo;

        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(musicInfo.getUri());
            mediaPlayer.prepare();
            mediaPlayer.start();
            isPause = false;
            UIUtils.getHandle().post(mBackgroudRunable);
            if (mListener != null) {
                mListener.onChange(mPlayingMusic);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 判断是否是在正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }

    /**
     * 判断是否是暂停的
     *
     * @return
     */
    public boolean isPause() {
        return mediaPlayer != null && isPause;
    }

    /**
     * 继续播放
     * 重新开始; 恢复
     *
     * @return
     */
    public int resume() {
        if (!isPause()) {
            return -1;
        }
        mediaPlayer.start();
        UIUtils.getHandle().post(mBackgroudRunable);
        Log.d("sp", "mListener.onPlayerResume(212121)***********");
        isPause = false;
        if (mListener != null) {
            mListener.onPlayerResume();
            Log.d("sp", "mListener.onPlayerResume()***********");
        }
        return mPlayingPosition;

    }

    /**
     * 暂停播放
     * @return
     */
    public int pause() {
        if (!isPlaying()) {
            return -1;
        }
        mediaPlayer.pause();
        UIUtils.getHandle().post(mBackgroudRunable);
        isPause = true;

        if (mListener != null) {
            mListener.onPlayerPause();

        }
        return mPlayingPosition;
    }

    public void next() {
        play(mPlayingPosition + 1);
    }

    public void prev() {
        play(mPlayingPosition - 1);
    }


    public void playPause() {
        if (isPlaying()) {
            pause();
        } else if (isPause()) {
            resume();
        } else {
            play(getPlayingPosition());
        }
    }

    /**
     * 获取正在播放的本地歌曲的序号
     */
    public int getPlayingPosition() {
        return mPlayingPosition;
    }

    /**
     * 获取正在播放的歌曲[本地|网络]
     */
    public MusicInfo getPlayingMusic() {
        return mPlayingMusic;
    }

    /**
     * 删除或下载歌曲后刷新正在播放的本地歌曲的序号
     */
    public void updatePlayingPosition() {
        int position = 0;
        long id = Preferences.getCurrentSongId();
        for (int i = 0; i < getMusicList().size(); i++) {
            if (getMusicList().get(i).getId() == id) {
                position = i;
                break;
            }
        }
        mPlayingPosition = position;
        Preferences.saveCurrentSongId(getMusicList().get(mPlayingPosition).getId());
    }


    /**
     * 用一个线程在后台来更新时间的进度，在Handler延时发用去更新
     */
    private Runnable mBackgroudRunable = new Runnable() {
        @Override
        public void run() {
            if (isPlaying() && mListener != null) {
                mListener.onPublish(mediaPlayer.getCurrentPosition());
            }
            UIUtils.getHandle().postDelayed(mBackgroudRunable, TIME_UPDATE);
        }
    };
    public void startQuitTimer(long milli) {
        stopQuitTimer();
        if (milli>0){
            quitTimerRemain=milli+DateUtils.SECOND_IN_MILLIS;
            UIUtils.getHandle().post(mQuitRunable);
        }else {
            quitTimerRemain=0;
            if (mListener!=null){
                mListener.onTimer(quitTimerRemain);
            }
        }
    }
    private void stopQuitTimer() {
        UIUtils.getHandle().removeCallbacks(mQuitRunable);
    }

    private Runnable mQuitRunable = new Runnable() {
        @Override
        public void run() {
            quitTimerRemain -= DateUtils.SECOND_IN_MILLIS;
            if (quitTimerRemain >= 0) {
                if (mListener != null) {
                    mListener.onTimer(quitTimerRemain);
                }
                UIUtils.getHandle().postDelayed(this, DateUtils.SECOND_IN_MILLIS);
            } else {
                SystemUtils.clearStack(sActivityStack);
                stop();
            }
        }
    };
    public void stop() {
        pause();
        stopQuitTimer();
        mediaPlayer.reset();
        mediaPlayer.release();
        mediaPlayer=null;
        stopSelf();
    }

    public static void removeFromStack(BaseActivity activity) {
        sActivityStack.remove(activity);
    }
    public static void addToStack(BaseActivity activity) {
        sActivityStack.add(activity);
    }
//    当加载的资源执行完了调用这个方法
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        next();
    }

    public class PlayBinder extends Binder{
        public PlayMusicService getService(){
            return PlayMusicService.this;
        }
    }
}
